package cn.yzgy.yzgyoa.common.service.impl;

import cn.yzgy.yzgyoa.common.entity.ReportRecord;
import cn.yzgy.yzgyoa.common.mapper.ReportRecordMapper;
import cn.yzgy.yzgyoa.common.service.IReportRecordService;
import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.entity.SysFileInfo;
import cn.yzgy.yzgyoa.common.exception.SystemException;
import cn.yzgy.yzgyoa.common.utils.Base64Util;
import cn.yzgy.yzgyoa.common.utils.ExportUtil;
import cn.yzgy.yzgyoa.ucenter.entity.UserInfoDetail;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yqsen
 * @since 2020-10-22
 */
@Service
public class ReportRecordServiceImpl extends ServiceImpl<ReportRecordMapper, ReportRecord> implements IReportRecordService {

    @Override
    public void fileDownload(String id, HttpServletResponse response, UserInfoDetail curUser) throws IOException {

        ReportRecord reportRecord = baseMapper.selectOne(new QueryWrapper<ReportRecord>()
                                            .lambda().eq(ReportRecord::getDownloadId,id));

        if(!curUser.getUid().equals(reportRecord.getCreateBy())){
            throw new SystemException(StatusCode.EXCEPTION,"此报表创建人非当前操作员，无法下载！");
        }
        ExportUtil.outPutFile(reportRecord,response);
    }

    @Override
    public void uploadFileDownload(String id, HttpServletResponse response) throws IOException {
        //获取文件对象
        SysFileInfo sysFileInfo = new SysFileInfo()
                .selectOne(new QueryWrapper<SysFileInfo>().lambda().eq(SysFileInfo::getFileId, id));

        File file = new File(sysFileInfo.getFilePath());
        if (file.exists()) {
            response.setContentType(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(sysFileInfo.getFilePath()));
            //格式化票据对应时间
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sysFileInfo.getFileName(), "UTF-8"));
            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
            while (is.read(buf) != -1) {
                os.write(buf, 0, buf.length);
                os.flush();
            }
        }else{
            throw new SystemException(StatusCode.EXCEPTION,"文件未找到或文件不存在！");
        }
    }

    @Override
    public String getBase64(String id) {
        //获取文件对象
        SysFileInfo sysFileInfo = new SysFileInfo()
                .selectOne(new QueryWrapper<SysFileInfo>().lambda().eq(SysFileInfo::getFileId, id));
        File file = new File(sysFileInfo.getFilePath());

        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        try {
            is = new FileInputStream(file);
            outStream = new ByteArrayOutputStream();
            // 创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            // 每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            // 使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }

            // 对字节数组Base64编码
            return Base64Util.encode(outStream.toByteArray());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }
}
